package com.kuaihuoyun.ctms.api;

import com.kuaihuoyun.ctms.dto.*;
import retrofit2.Call;
import retrofit2.Response;
import retrofit2.http.Body;
import retrofit2.http.POST;

import java.io.IOException;

/**
 * Created by lxji on 2018/1/4.
 */
public class UserService extends BaseService {
    public UserService(String url) {
        super(url, null);
    }

    public CtmsResponse<AccessTokenResponse> generateAccessToken(String userName, String password) throws IOException {
        Call<CtmsResponse<AccessTokenResponse>> responseCall = retrofit.create(UserApi.class).generateAccessToken(
                AccessTokenRequest.builder().userName(userName).password(password).build());
        final Response<CtmsResponse<AccessTokenResponse>> response = responseCall.execute();
        if(!response.isSuccessful()) {
            return CtmsResponse.create(response);
        }

        return response.body();
    }

    public CtmsResponse<RefreshTokenResponse> refreshAccessToken(String userName, String refreshToken) throws IOException {
        Call<CtmsResponse<RefreshTokenResponse>> responseCall = retrofit.create(UserApi.class).refreshAccessToken(
                RefreshTokenRequest.builder().userName(userName).refreshToken(refreshToken).build());
        final Response<CtmsResponse<RefreshTokenResponse>> response = responseCall.execute();
        if(!response.isSuccessful()) {
            return CtmsResponse.create(response);
        }

        return response.body();
    }


    interface UserApi {
        @POST("/user/generate_access_token/v2")
        Call<CtmsResponse<AccessTokenResponse>> generateAccessToken(@Body AccessTokenRequest request) throws IOException;

        @POST("/user/refresh_access_token/v2")
        Call<CtmsResponse<RefreshTokenResponse>> refreshAccessToken(@Body RefreshTokenRequest request) throws IOException;
    }
}
